package com.founder.chd_daily_query.service.impl;

import com.founder.chd_daily_query.entity.file.FileLoadEntity;
import com.founder.chd_daily_query.repo.file.FileLoadRepo;
import com.founder.chd_daily_query.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.util.*;

@Service
public class FileServiceImpl implements FileService {

    @Value(value = "${file.load.address}")
    String loadPath;

    @Autowired
    FileLoadRepo fileLoadRepo;

    @Override
    public Map<String,Object> fileUpload(MultipartFile file) {
        Exception check=null;
        if(file ==null){
            return null;
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'),originalFilename.length());
        String uuidName = UUID.randomUUID().toString();
        File uploadFile = new File(loadPath+"/"+uuidName+suffix);
        try {
            //文件上传
            file.transferTo(Paths.get(uploadFile.getAbsolutePath()));
            //return "文件已经上传";
        } catch (IOException e) {
            check=e;
            e.printStackTrace();
        }
        //写入文件列表
        if(check==null){
            FileLoadEntity fileLoadEntity = new FileLoadEntity();
            fileLoadEntity.setFileId( UUID.randomUUID().toString().replace("-",""));
            fileLoadEntity.setFileMaskName(uuidName);
            fileLoadEntity.setFileSuffix(suffix);
            fileLoadEntity.setFileName(originalFilename);
            fileLoadEntity.setUploadTime(new Date());
            fileLoadRepo.save(fileLoadEntity);


        }

        return getList(0,10);
    }

    @Override
    public String fileDownload( String fileId, HttpServletResponse response) throws IOException {
        //查询文件
        FileLoadEntity fileLoadEntity =new FileLoadEntity();
        fileLoadEntity.setFileId(fileId);
        Example<FileLoadEntity> of = Example.of(fileLoadEntity);
        //根据id查询
        List<FileLoadEntity> allById = fileLoadRepo.findAll(of);
        if(allById.size()==0){
            return "无此文件，请联系管理员";
        }
        //拿到唯一的一条记录
        FileLoadEntity file = allById.get(0);
        try {
            File f =new File(loadPath+"/"+file.getFileMaskName()+file.getFileSuffix());
            //拿到文件输入流（buffered）避免过大流
            BufferedInputStream bufferedInputStream =new BufferedInputStream(new FileInputStream(f));
            //拿到输出流
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] outputbyte =new byte[1024];

            String fileName = file.getFileName();
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
            response.addHeader("Content-Length", String.valueOf(f.length()));
            response.setContentType("application/force-download");
           // response.setCharacterEncoding("utf-8");
            //写入文件到文件缓冲
            int i =bufferedInputStream.read(outputbyte);

            while(i!= -1){
                outputStream.write(outputbyte,0,outputbyte.length);
                //直接开启io
                outputStream.flush();
                i =bufferedInputStream.read(outputbyte);

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return "下载成功";

    }

    @Override
    public Map<String,Object>  getList(int page, int count) {
        Map<String,Object> res =new HashMap<String,Object>();
        long count1 = fileLoadRepo.count();
        PageRequest pageRequest =  PageRequest.of(page, count,Sort.by(Sort.Direction.DESC,"uploadTime"));
        Page<FileLoadEntity> all = fileLoadRepo.findAll(pageRequest);
        res.put("count",count1);
        res.put("data",all.getContent());
        return res;
    }

    @Override
    public String fileDelete(String id) {
        //开始查询文件有效性
        FileLoadEntity fileLoadEntity = new FileLoadEntity();
        fileLoadEntity.setFileId(id);

        Example<FileLoadEntity> of = Example.of(fileLoadEntity);
        List<FileLoadEntity> all = fileLoadRepo.findAll(of);
        if(all.size()==0){
            return "file not exist";
        }
        //拿到文件
        FileLoadEntity fileLoadEntity1 = all.get(0);
        //检查文件是不是真的存在？
        String fileMaskName = fileLoadEntity1.getFileMaskName();
        String fileSuffix = fileLoadEntity1.getFileSuffix();

        String searchPath =loadPath+"/"+fileMaskName+fileSuffix;

        File file = new File(searchPath);
        if(!file.exists()){
            //文件实际已经不存在了，属于事务残留
            //删除数据库记录
            fileLoadRepo.delete(fileLoadEntity1);
            return "file not exist";
        }

        boolean delete = file.delete();
        fileLoadRepo.delete(fileLoadEntity1);

        if(delete){
            return "success";
        }

        return "fail";
    }


}

